#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/9/1 19:34
# @Author  : 1823218990@qq.com
# @File    : main_recorded
# @Software: Pycharm
"""
https://www.gyan.dev/ffmpeg/builds/

https://cyfuture.dl.sourceforge.net/project/screencapturer/Setup%20Screen%20Capturer%20Recorder%20v0.12.11.exe?viasf=1

https://sourceforge.net/projects/screencapturer/files/

"""
import sys
import os
import subprocess
from datetime import datetime
from multiprocessing import Process
from tkinter import Tk
import tkinter as tk
CODE_ERROR = -1
real_cfile = os.path.abspath(__file__)
real_path = os.path.dirname(real_cfile)
if sys.platform.startswith("win"):
    ffmpeg_bin = os.path.join(real_path, "ffmpeg\\bin\\ffmpeg.exe")
    ffprobe_bin = os.path.join(real_path, "ffmpeg\\bin\\ffprobe.exe")
else:
    raise RuntimeError("无法再该平台上运行")
sys.path.append(real_path)

MUSIC_PATH = "\\opt\\music"
if not os.path.exists(MUSIC_PATH):
    os.makedirs(MUSIC_PATH, exist_ok=True)


def exe_cmd(cmd, timeout=10, logger=None):
    try:
        s = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = s.communicate(timeout=timeout)
        code = s.returncode
        if logger is not None and code != 0:
            logger.info("code:{} out:{} err:{}".format(code, stdout, stderr))
        if code != 0:
            return code, "{}".format(stderr.decode('utf-8'))
        else:
            return code, "{}".format(stdout.decode('utf-8'))
    except Exception as e:
        if logger is not None:
            logger.error(e)
        return CODE_ERROR, e


class MainRecorderd(object):
    def __init__(self, ui, name, duration, size=None):
        self._duration = None
        self._name = None
        self._size = None
        self.ui = ui

        self._name = name
        self._duration = duration
        self._size = size
        self._v_type = '.mp4'
        self._music_file_path = None

        self.ui.title('录屏软件         --wgq 2025.9.1')
        self.ui.geometry('400x130+1080+100')  # 宽x高+偏移量
        self.setupui()

    def setupui(self):
        name_label = tk.Label(self.ui, text=u'歌名：')
        name_label.grid(row=1, column=1)

        name_var = tk.StringVar()
        name_var.set(self._name)
        self.name_input = tk.Entry(self.ui, textvariable=name_var, width=40)
        self.name_input.grid(row=1, column=2, padx=10, pady=5)

        time_label = tk.Label(self.ui, text=u'时间：')
        time_label.grid(row=2, column=1)

        time_var = tk.StringVar()
        time_var.set(self._duration)
        self.time_input = tk.Entry(self.ui, textvariable=time_var, width=40)
        self.time_input.grid(row=2, column=2, padx=10, pady=5)
        self.time_input.config(text=self._duration)

        btn_run = tk.Button(self.ui, text=u'录制', width=10, command=self.do)
        btn_run.grid(row=3, column=1)

        self.msg_label = tk.Label(self.ui, text=u'')
        self.msg_label.grid(row=4, column=2)

    def str_time_to_second(self):
        temp_dt = datetime.strptime(self._duration, "00:%M:%S")
        return temp_dt.hour * 3600 + temp_dt.minute * 60 + temp_dt.second

    def do(self):
        try:
            self._name = self.name_input.get()
            self._duration = self.time_input.get()
            if isinstance(self._duration, str):
                # self._duration = datetime.strftime("00:%M:%S")
                self._duration = self.str_time_to_second()
            self.msg_label.config(text="开始录制..." + self._name)
            print("init: ", self._name, self._duration)

            self._music_file_path = os.path.join(MUSIC_PATH, self._name + self._v_type)

            if self._size is None:
                self._size = '1094:730:0:0'  # 宽度:高度:起始X坐标:起始Y坐标
            if os.path.exists(self._music_file_path):
                os.remove(self._music_file_path)
            cmd = '{ffmpeg} -f gdigrab -i desktop -f dshow -i audio="virtual-audio-capturer" ' \
                  '-c:v libx264 -c:a aac -t {time} -vf "crop={size}" {name}'.format(
                ffmpeg=ffmpeg_bin, name=self._music_file_path, time=self._duration, size=self._size
            )
            print(cmd)
            # code, msg = exe_cmd(cmd, timeout=self._duration + 2)
            # code, msg = subprocess.getstatusoutput(cmd)
            a = Process(target=exe_cmd, args=(cmd, self._duration+2))
            a.start()
            a.join()
            # os.system(cmd)
            code, msg = "", ""
            print("code:", code)
            print("msg: ", msg)
            show_str = "录制结束\n" + msg
        except Exception as e:
            show_str = str(e)
        self.msg_label.config(text=show_str)


if __name__ == '__main__':
    name = "a_test"
    duration = "00:00:06"
    size = '1094:730:0:0'
    ui = Tk()
    rd = MainRecorderd(ui, name, duration)
    # rd.do()
    rd.ui.mainloop()
